import fetch from "node-fetch";
import common from "../../lib/common/common.js";
import plugin from "../../lib/plugins/plugin.js";
import fs from 'fs'
import yaml from "yaml"
import sharp from 'sharp'
import pLimit from 'p-limit'

let maxnum = 30  //并发限制

let cooldowns = new Map();
let NumReg = '[一壹二两三四五六七八九十百千万亿\\d]+'
export class iw233 extends plugin {
    constructor() {
        super({
            /** 功能名称 */
            name: 'iw233',
            /** 功能描述 */
            dsc: 'iw233',
            /** https://oicqjs.github.io/oicq/#events */
            event: 'message',
            /** 优先级，数字越小等级越高 */
            priority: 500,
            rule: [
                {
                    reg: '^#来份(.*)$',
                    fnc: 'ciyuan'
                }, 
				
            ]
        })
    }

 async ciyuan(e) {
	if (!e.isGroup) {
	    return;
    }
	let groupId = e.group_id
    let cfg = await loadcfg(groupId)
	if (!cfg && !e.isMaster) return
	
    if (!cfg.setu && !e.isMaster) {
	     logger.mark(`${groupId} 涩图权限 ${cfg.setu}`)
         return;
    }
	let keyword = e.msg.replace(/#|来份/g, "").trim();
	let num = 10
    let Match = e.msg.match(new RegExp(`(${NumReg})(张|份)`));
    if (Match) {
        num = Number(Match[1]);
        if (isNaN(num)) {
            return;
        }
        keyword = keyword.replace(Match[0], "").trim();  // 去掉匹配的页码部分
    }
	if (num>100){
		num = 10
	}  
    let keymap = {
		"二次元": `https://iw233.cn/api.php?sort=random&type=json&num=${num}`,
		"兽耳": `https://iw233.cn/api.php?sort=cat&type=json&num=${num}`,
		"推荐": `https://iw233.cn/api.php?sort=top&type=json&num=${num}`,
		"银发": `https://iw233.cn/api.php?sort=yin&type=json&num=${num}`,
		"星空": `https://iw233.cn/api.php?sort=xing&type=json&num=${num}`,
		"竖屏壁纸": `https://iw233.cn/api.php?sort=mp&type=json&num=${num}`,
		"横屏壁纸": `https://iw233.cn/api.php?sort=pc&type=json&num=${num}`
	}		
    if (!keymap[keyword] && keyword != "三次元") {
        e.reply("仅支持关键词【二次元，三次元，推荐，银发，兽耳，星空，竖屏壁纸，横屏壁纸】",false,{ recallMsg: 10 });
        return ;
    }
	if (!e.isMaster ) {
	    const cooldown = cooldowns[groupId];
	    if (cooldown && cooldown > Date.now()) {
            const remainingTime = Math.ceil((cooldown - Date.now()) / 1000);
            e.reply(`lsp注意身体，请${remainingTime}秒后再来～`,false,{ recallMsg: 5 });
            return;
        }
	}
	
    let response = ''
	let res = ''
	let msgs = []
	// 设置并发限制
    const limit = pLimit(maxnum)

	if (keyword === "三次元") {
		const randomIndex = Math.floor(Math.random() * 500) + 1;
		const page = Math.ceil((randomIndex) / 10);  
	    try {
            response = await fetch(`https://yingtall.com/wp-json/wp/v2/posts?page=${page}`);
	        res = await response.json();
		} catch (error) {
			e.reply('请求失败',true,{ recallMsg: 5 })
			return
		}
		if (!e.isMaster ) {
		    cooldowns[groupId] = Date.now() + cfg.cd * 1000
		}
		
	    e.reply(`${keyword}马上来力，请稍等...`,false,{ recallMsg: 5 })
		
	    // 使用 Promise.all 和 p-limit 并行下载图片
        await Promise.all(res.map((k, index) => limit(async () => {
			const content = k.content;
			if (!content && !content.rendered) return false
			let ma = [`${k.title.rendered.replace(/\[.*?\]/g, '')}\n`]
				
            const imgRex = /<img.*?src="(.*?)"[^>]+>/g;
			let img
			while (img = imgRex.exec(content.rendered)) {
			    try {
					const image = await fetch(encodeURI(img[1]));
                    const imagedate = Buffer.from(await image.arrayBuffer());
                    const flippedImage = await sharp(imagedate).flop().toBuffer();
                    ma.push(segment.image(flippedImage))  
					logger.info(`${keyword} 图片${index+1}处理 ok`)
				} catch(error) {	
                    ma.push(segment.image(encodeURI(img[1])))
					logger.error(`${keyword} 图片${index+1}处理 error`)
				}			
            }
			msgs.push(ma)
        })));
		
		let ForwardMsg = await common.makeForwardMsg(e,msgs)	  
			await e.reply(ForwardMsg,false,{ recallMsg: cfg.recall })
	}
		  
    else {	
		try{
            response = await fetch(keymap[keyword]);
            res = await response.json();
			res = res.pic
		} catch (error) {
			//e.reply('请求失败',true,{ recallMsg: 5 })
		    //return
			logger.info(`iw233失效，切换anosu源`)
			keymap = {
			  "二次元": `https://api.anosu.top/api?sort=setu&type=json&num=${num}`,
			  "推荐": `https://api.anosu.top/api?sort=setu&type=json&num=${num}`,
			  "兽耳": `https://api.anosu.top/api?sort=furry&type=json&num=${num}`,
			  "银发": `https://api.anosu.top/api?sort=silver&type=json&num=${num}`,
			  "星空": `https://api.anosu.top/api?sort=starry&type=json&num=${num}`,
			  "竖屏壁纸": `https://api.anosu.top/api?sort=mp&type=json&num=${num}`,
			  "横屏壁纸": `https://api.anosu.top/api?sort=pc&type=json&num=${num}`
		    }
            try{
                response = await fetch(`${keymap[keyword]}&time=${Date.now()}`);
                res = await response.json();
				res = res.pics
		    } catch (error) {
			    e.reply('请求失败',true,{ recallMsg: 5 })	
                return		
			}				
		}
		cooldowns[groupId] = Date.now() + cfg.cd * 1000;
        e.reply(`${keyword}马上来力，数量${num}...`,false,{ recallMsg: 5 })
		
		// 使用 Promise.all 和 p-limit 并行下载图片
        await Promise.all(res.map((k, index) => limit(async () => {
            try {
				const image = await fetch(k);
                const imagedate = Buffer.from(await image.arrayBuffer());
                const flippedImage = await sharp(imagedate).flop().toBuffer();
                msgs.push(segment.image(flippedImage))  
			    logger.mark(`${keyword} 图片${index+1}处理 成功`)
			} catch(error) {	
                msgs.push(segment.image(res.pic[i]))
				logger.error(`${keyword} 图片${index+1}处理 失败`)
			}	
        })));
		 
	    let ForwardMsg = await common.makeForwardMsg(e,[msgs])	
	   		await e.reply(ForwardMsg,false,{ recallMsg: msgs.length > 10 ? cfg.recall : 60 })
	}
    return true
  }

}

async function loadcfg(id) {
	let file = `data/pixiv.yaml`
    if (!fs.existsSync(file)) return false
	
    let data = yaml.parse(fs.readFileSync(file, 'utf8'))
	if (!data[id]) return false
	
	return data[id]
}




